package cn.jiedh.app.meiweidk.base;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import org.xutils.common.Callback;
import org.xutils.ex.HttpException;

import java.lang.ref.WeakReference;
import java.util.Map;
import java.util.WeakHashMap;

import butterknife.ButterKnife;
import cn.jiedh.app.meiweidk.MainActivity;
import cn.jiedh.app.meiweidk.MyWebActivity;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.LoadDialog;
import cn.jiedh.app.meiweidk.Utils.tool.L;
import cn.jiedh.app.meiweidk.Utils.tool.StatusBarUtil;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.app.EnvConfig;
import cn.jiedh.app.meiweidk.homepage.GreenLandActivity;
import cn.jiedh.app.meiweidk.mine.MyQuotaActivity;
import cn.jiedh.app.meiweidk.network.AsyncWebServer;
import cn.jiedh.app.meiweidk.network.ResponseFailure;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;


/**
 * @name：
 * @author： 孙科技
 * @phone： 13308334117
 * @createTime： 2017/3/10
 * @modifyTime： 2017/3/10
 * @explain：
 */
public abstract class BaseActivity extends AppCompatActivity {
    protected Activity activity;
    private View view;
    private LoadDialog loadDialog;
    public AsyncWebServer mAWs;
    String TAG = "BaseActivityTag";
    WeakHashMap<String, WeakReference<Callback.Cancelable>> requesMap;

    Map<String, Object> map;
    ResponseSuccess<T> success;
    String url;
    ResponseFailure failure;
    boolean isEncrypt;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        activity = this;

        if(activity instanceof MyQuotaActivity || activity instanceof MainActivity||activity instanceof GreenLandActivity){
            cn.jiedh.app.meiweidk.Utils.tool.StatusBarUtil.transparencyBar(this);
        }else{
            setStatusBar();
        }
        super.onCreate(savedInstanceState);
        L.d(TAG, getClass().getCanonicalName());
        mAWs = AsyncWebServer.getInstance(this);
        requesMap = new WeakHashMap<>();
        setContentView(getLayoutView());
        ButterKnife.bind(this);
        setBack(true);
        initView(view);
        initData();
        L.d("页面", getClass().getCanonicalName());
    }


    public void setStatusBar() {
//        StatusBarUtil.setStatusBarColor(this, R.color.title_bg);
        StatusBarUtil.statusBarLightMode(this);
        com.jaeger.library.StatusBarUtil.setColor(this, Color.WHITE,0);
    }

    protected abstract int getLayoutView();

    protected abstract void initView(View view);

    protected abstract void initData();


    public void showLoadingDialog() {
        if (loadDialog != null && loadDialog.isShowing()) {
            loadDialog.dismiss();
        }
        loadDialog = new LoadDialog(this);
        loadDialog.show();

//        loadDialog.setCanceledOnTouchOutside(true);//点击Dialog以外的区域不允许取消
//        loadDialog.setCancelable(true);//禁止系统返回键的取消Dialog

    }

    public void dismissLoadingDialog() {
        if (loadDialog != null && loadDialog.isShowing()) {
            loadDialog.dismiss();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        L.i(TAG, ">>>>>>>>>>用户数据" + keyCode);
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                L.d(TAG, "KeyEvent.KEYCODE_MENU");
                Toast.makeText(this, "KeyEvent.KEYCODE_MENU", Toast.LENGTH_LONG);
                break;
            case KeyEvent.KEYCODE_HOME:
                L.d(TAG, "KeyEvent.KEYCODE_HOME");
                finish();
                Toast.makeText(this, "KeyEvent.KEYCODE_HOME", Toast.LENGTH_LONG);
                break;
            case KeyEvent.KEYCODE_BACK:
                L.d(TAG, "KeyEvent.KEYCODE_BACK");
                Toast.makeText(this, "KeyEvent.KEYCODE_BACK", Toast.LENGTH_LONG);
                break;
            default:
                L.d(TAG, "没有匹配的");
                Toast.makeText(this, "KeyEvent.没有匹配的", Toast.LENGTH_LONG);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        cancelAllRequest();//取消网络请求
        super.onDestroy();
    }

    public void request(Activity activity, String url, Map<String, Object> map, boolean isEncrypt
            , ResponseSuccess success, ResponseFailure failure) {
        map.put("timeStamp", System.currentTimeMillis());
        requesMap.put(EnvConfig.BASE_URL + url, new WeakReference<>(mAWs.request(activity, EnvConfig.BASE_URL + url, UrlUtils.getMaps(map, isEncrypt), isEncrypt, success, failure)));
    }

    public void request(Activity activity, String url, Map<String, Object> map, boolean isEncrypt
            , ResponseSuccess success) {
        map.put("timeStamp", System.currentTimeMillis());
        requesMap.put(EnvConfig.BASE_URL + url, new WeakReference<>(mAWs.request(activity, EnvConfig.BASE_URL + url, UrlUtils.getMaps(map, isEncrypt), isEncrypt, success, this::defaultRequestError)));
    }

    public void request(String url, Map<String, Object> map, boolean isEncrypt, ResponseSuccess success, ResponseFailure failure) {

        if (this instanceof BaseActivity) {
            BaseActivity ba = (BaseActivity) this;
            ba.request(ba, url, map, isEncrypt, success, failure);

        }
    }

    public void request(String url, Map<String, Object> map, boolean isEncrypt, ResponseSuccess success) {

        if (this instanceof BaseActivity) {
            BaseActivity ba = (BaseActivity) this;
            ba.request(ba, url, map, isEncrypt, success);
        }
    }

    /**
     * 取消所有请求
     */
    private void cancelAllRequest() {
        if (requesMap != null && requesMap.size() > 0) {
            for (WeakReference<Callback.Cancelable> request : requesMap.values()) {
                if (request.get() != null) {
                    request.get().cancel();
                }
            }
        }
    }

    /**
     * 设置标题
     */
    public void setTitle(String title) {
        TextView titleView = (TextView) findViewById(R.id.bar_tv_title);
        if (titleView != null && !TextUtils.isEmpty(title)) {
            titleView.setText(title);
        }
    }

    public void setBack(boolean isCanBack) {
        if (isCanBack) {
            View back = findViewById(R.id.bar_img_back);
            if (back != null) {
                back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            }
        }
    }

    /**
     * 取消特定网络请求
     *
     * @param url
     */
    public void cancelRequest(String url) {
        if (requesMap != null && requesMap.size() > 0) {
            for (String key : requesMap.keySet()) {
                if (key.equals(url)) {
                    if (requesMap.get(url).get() != null) {
                        requesMap.get(url).get().cancel();
                    }
                    break;
                }
            }
        }
    }

    public void defaultRequestError(HttpException error, String msg) {
        dismissLoadingDialog();
        if (!TextUtils.isEmpty(msg)) {
            T.showShortToast("请求失败");
        }
    }


}
